package srzy.module

import java.io.File
import srzy.common.Logging
import srzy.common.Config
import srzy.data.PublicData
import srzy.module._
import spray.json._
import DefaultJsonProtocol._

object CaseDeal extends Logging {

  var l = List[AbsCaseDeal](CleanDir, CacheInit, RBInMemoryInit, SMInMemoryInit, DCCMsgDeal, ReadCdrFile, RBMsgComp, CdrComp)
  //    CleanDir, ShellInit, RBInit, DCCMsgDeal, ReadCdrFile, CdrComp, RBMsgComp) 

  def getCaseInfo(caseId: Int) = {
    PublicData.caseInfos.apply(caseId)
  }

  def dealAllCase = {
    logger.debug("Begin to deal")
    logger.debug("caseNames:" + PublicData.caseInfos.map(x => x.caseName).mkString(" "))
    val dbRecFlag: Boolean =
      if (Config.getValue("root", "config", "DBRecFlag").toUpperCase() == "TRUE") true
      else false
    logger.debug("dbRecFlag:" + dbRecFlag)
    for (i <- 0 until PublicData.caseInfos.length) {
      try {
        for (e <- l) {
          val className = ("""[\w]+""".r findAllIn e.getClass().getName()).toList.last
          logger.debug(className + " begin deal " + (i + 1) + ":" + getCaseInfo(i).caseName)
          e.setCaseId(i)
          e.deal
          logger.debug(className + " deal over " + (i + 1) + ":" + getCaseInfo(i).caseName)
        }
      } catch {
        case ex: Exception =>
          {
            logger.error(ex.getMessage(), ex)
            getCaseInfo(i).errLog = ex.getMessage()
            //            getCaseInfo(i).caseResult = false
          }
      }
      logger.debug("FileRec begin deal " + (i + 1) + ":" + getCaseInfo(i).caseName)
      FileRec.setCaseId(i)
      FileRec.deal
      logger.debug("FileRec deal over " + (i + 1) + ":" + getCaseInfo(i).caseName)

      if (dbRecFlag == true) {
        logger.debug("DBRec begin deal " + (i + 1) + ":" + getCaseInfo(i).caseName)
        DBRec.setCaseId(i)
        DBRec.deal
        logger.debug("DBRec deal over " + (i + 1) + ":" + getCaseInfo(i).caseName)
      }
    }

    val caseInfos = PublicData.caseInfos.map(x => {
      (x.caseName, (x.realFullCdrs.toJson.prettyPrint,
        x.realReceDCCMsg.mkString("\n-----\n"),
        x.realReceFromSMMsg.mkString("\n"),
        x.realSendToSMMsg.mkString("\n")))
    }).toMap

    logger.debug("begin write json file")
    srzy.common.Common.writeToFile("data.json", caseInfos.toJson.prettyPrint, "UTF-8")
    //    val caseInfos = srzy.common.Common.readFromFile("data.json", "UTF-8").mkString("\n").asJson.convertTo[scala.collection.immutable.Map[String, (String, String, String, String)]]
    logger.debug("write json file over")

    logger.debug("Deal case over")

  }
}



